package ws

import (
	"encoding/json"
	"fmt"
	"gin_websocket_demo/sf"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var clientList []*websocket.Conn

//设置websocket
//CheckOrigin防止跨站点的请求伪造
var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// WsConnect
func WsConnect(c *gin.Context) {
	//升级get请求为webSocket协议
	client, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer client.Close() //返回前关闭
	clientId := sf.GenId()
	clientList = append(clientList, client)
	//写入ws数据
	data := map[string]int64{
		"client_id": clientId,
	}
	msg, _ := json.Marshal(data)
	pushMsg(client, string(msg))
	checkLine(client)
	for {

	}
}

func UserLogin(c *gin.Context) {

}

// pushAll 广播消息
func pushAll(msg string) {
	for _, client := range clientList {
		pushMsg(client, msg)
	}
}

// pushMsg 推送消息
func pushMsg(client *websocket.Conn, msg string) {
	client.WriteMessage(websocket.TextMessage, []byte(msg))
}

func checkLine(client *websocket.Conn) {
	go func() {
		for {
			time.Sleep(10 * time.Second)
			err := client.WriteMessage(websocket.TextMessage, []byte(`{"ping":"pong"}`))
			if err != nil {
				fmt.Println("client已下线")
				return
			}
		}
	}()
}
